<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>作品上传-个人中心-魔步网</title>
<?php include_once(VIEWPATH."public/header_title.php");?>
<link href="<?php echo _get_cfg_path('css')?>base.css" type="text/css" rel="stylesheet" />
<link href="<?php echo _get_cfg_path('css')?>common.css" type="text/css" rel="stylesheet" />
<link href="<?php echo _get_cfg_path('lib')?>uploadify/uploadify.css" type="text/css" rel="stylesheet" />
<!--[if IE 6]>
<script src="js/DD_belatedPNG.js" type="text/javascript" ></script>
<script>DD_belatedPNG.fix('a,img');</script>
<![endif]-->
<style>
.upload_list_photo li{position:relative;}
.progress{display:inline-block;position:absolute;left:0;top:50%;height:40px;line-height:40px;margin-top:-20px;text-align:center;color:#fff;font-size:14px;background:rgba(0, 0, 0, 0.4);}
</style>
</head>
<body>
<?php include_once(VIEWPATH."public/header.php");?>
<div class="mainbody" id="mainbody">
    <div class="container mrgB30">
        <div class="member clearfix">
            <?php include_once(VIEWPATH."m/public/left_menu.php");?>
            <div class="fr uc_content">
                <?php include_once(VIEWPATH."m/public/notice.php");?>
                <div class="clearfix uitopg">
                    <div class="transa">
                        <div class="aut_bti"><h3>作品上传</h3></div>
                        <div class="uploadworks">
                            <div class="upload_top clearfix">
                              <p class="fl">上传照片</p>
                              <div class="fl photo_select">
                                  <select name="st_select" id="st_select">
                                  <!--<option value="">请选择要上传的相册</option>-->
                                  <?php foreach ($albumlist as $key => $a): ?>
                                  <option _val="<?php echo $a['id']?>" value="<?=_get_key_val($a['id'])?>" <?php echo (!empty($albumid) && $albumid == $a['id']) ? 'selected="selected"' : ''?> ><?=$a['title']?></option>
                                  <?php endforeach;?>
                                  </select>
                              </div>
                              <?php /*?><div class="fl st_select">
                                    <input type="hidden" name="" class="st_select_input">
                                    <div class="st_select_txt">请选择要上传的相册</div>
                                    <div class="st_select_btn"></div>
                                    <ul class="st_select_list" style="display: none;">
                                        <?php foreach ($albumlist as $key => $a): ?>
                                        <li _val="<?=_get_key_val($a['id'])?>"><?=$a['title']?></li>
                                        <?php endforeach;?>
                                    </ul>
                                </div><?php */?>
                                <!--<p class="fr"><a href="##">反馈问题</a><a href="##">使用帮助</a></p>-->
                              <!--<div class="fr photoback"><a href="<?php echo (('' != ($this->input->get('agid'))) && (2 == $this->loginUsertype)) ? '/m/works?agid='.$this->input->get('agid') :'/m/works';?>" title="返回">返回</a></div>-->
                            </div>
                            
                            <div class="upload_list upload_list_photo">
                              <ul class="clearfix" id="X-photo-list">
                              	<?php
                                if(!empty($photolist)):
									foreach($photolist as $key=>$a) :?>
                                    <li>
                                        <div class="udl_bti_img"><img src="<?=$a['img']?>"></div>
                                        <div class="udl_bti"><p><?=$a['title']?></p><a _val="<?=_get_key_val($a['id'])?>" class="delete" title="删除" onClick="filedelete(this,'<?php echo _get_key_val($a['id'])?>')"></a></div>
                                    </li>
                                    <?php endforeach;
                                    else : ?>
<!--                                     请先选择相册，上传图片,系统将默认最后一张图为封面图！！！ -->
				<?php endif?>
                                </ul>
                            </div>
                            <div class="btn-wraper upload_bottom aut_tab clearfix">
                                <input type="button" value="选择图片" id="browse" class="but"/>
                                <input type="submit" value="开始上传" id="start_upload" class="but" style="margin:0 20px"/>
                                <a class="but" href="<?php echo (('' != ($this->input->get('agid'))) && (2 == $this->loginUsertype)) ? '/m/works?agid='.$this->input->get('agid') :'/m/works';?>" title="返回">返回</a>
                            </div>    
                        </div>
                    </div>
                </div>

            </div>
        </div>
        <div class="help_bottom"></div>
    </div> 
</div>
<!--mainbody-->
<?php include_once(VIEWPATH."public/footer.php");?>

</body>
<script type="text/javascript" src="<?php echo _get_cfg_path('js')?>jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="<?php echo _get_cfg_path('js')?>common.js"></script>
<script type="text/javascript" src="<?php echo _get_cfg_path('js')?>jquery.SuperSlide.2.1.1.js"></script>
<script>jQuery(".txtScroll-top").slide({titCell:".hd ul",mainCell:".bd ul",autoPage:true,effect:"topLoop",autoPlay:true});</script>
<?php /*?><script type="text/javascript" src="<?php echo _get_cfg_path('js')?>pages/m/photo.js"></script><?php */?>
<script type="text/javascript" src="<?php echo _get_cfg_path('js')?>plupload/plupload.full.min.js"></script>
<script>
<?php $timestamp = $this->timestamp;?>
$('#st_select').change(function(){
	var selectedVal = $(this).val();
        var urlSltVal = $("#st_select option:selected").attr('_val');
        window.location.href = "/m/works/photo/"+urlSltVal+"<?php if($this->input->get('agid')) echo '?agid='.$this->input->get('agid'); else echo '';?>";
//	$.ajax( {
//		url:'/m/works/getphoto',
//		data:{
//                    albumid : selectedVal
//		},
//		type:'post',
//		cache:false,
//		dataType:'json',
//		success:function(res) {
//			if(res.code ==200 ){
//				var html = '';
//				$.each(res.data.photolist,function(n,item) {
//					html += '<li><div class="udl_bti_img"><img src="'+item.img+'"></div><div class="udl_bti"><p>'+item.title+'</p><a _val="'+item.id+'" class="delete" onclick=filedelete(this,"'+item.id+'")></a></div></li>'
//				});
//				$('#X-photo-list').html(html);
//			}else{
//				var msg = '';
//				$.each(res.data.error_messages,function(n,value) {
//					msg +=value+'\n';
//				});
//				if(msg!='')
//					alert(msg);
//			}
//		 }
//	});
})
var selectVal = $('#st_select').val();
//实例化一个plupload上传对象
var uploader = new plupload.Uploader({
    browse_button : 'browse',                  		//触发文件选择对话框的按钮，为那个元素id
    url : '/public/upload/uploadphotoimg', 			//服务器端的上传页面地址
    flash_swf_url : 'plupload/Moxie.swf',           //swf文件，当需要使用swf方式进行上传时需要配置该参数
    silverlight_xap_url : 'plupload/Moxie.xap',     //silverlight文件，当需要使用silverlight方式进行上传时需要配置该参数

    file_data_name : 'Filedata',

    multipart: true,
    multipart_params: {
         timestamp : '<?php echo $timestamp;?>',
         uid : "<?php if($this->input->get('agid')) echo $this->input->get('agid'); else echo $this->thatUser['id'];?>",
         type : 'photo',
         albumid : selectVal,
         token : '<?php echo md5($this->config->item('encryption_key') . $timestamp );?>',
    },

    filters: {
      mime_types : [ //只允许上传图片
        { title : "Image files", extensions : "jpg,jpeg,gif,png" }, 
      //  { title : "Zip files", extensions : "zip,rar,7z" },
      //  { title : "Office files", extensions : "doc,docx,xls,xlsx,ppt,txt" }
      ],
      max_file_size : '10240kb', //最大只能上传10240kb的文件
      prevent_duplicates : true //不允许选取重复文件
    }
});

uploader.init(); //初始化

//绑定文件添加进队列事件
uploader.bind('FilesAdded',function(uploader,files){        
    for(var i = 0, len = files.length; i<len; i++){
        var file_name = files[i].name; //文件名

        //构造html来更新UI     
        var html = '<li id="file-' + files[i].id +'"><div class="udl_bti_img"></div><div class="udl_bti"><p>'+file_name+'</p><span class="progress"><i id="file-' + files[i].id + '-size" class="file-size"></i></span><a class="delete file_delete" title="删除" data-val='+ files[i].id +'></a></div></li>';
   		//<input name="data_arr" type="hidden" id="file-' + files[i].id +'" value=""/>
        !function(i){
            previewImage(files[i],function(imgsrc){
                $('#file-'+files[i].id+ ' .udl_bti_img').append('<img src="'+ imgsrc +'" />');
            })
        }(i);

        $(html).appendTo('#X-photo-list');
    }
// 	alert('图片添加成功，点击上传图片！！');
	
	//$('.file_delete').click(function() {
//		$(this).parents('li').remove();
//	});
});
//图片删除，对当前未上传的文件做删除操作
$(document).on('click','.file_delete',function(){
	$(this).parents('li').remove();
	//uploader.removeFile($(this).attr("data-val"));
	var toremove = '';
	var id=$(this).attr("data-val");
	for(var i in uploader.files){
		if(uploader.files[i].id === id){
			toremove = i;
		}
	}
	uploader.files.splice(toremove, 1);
	console.log("XXX"+$(this).attr("data-val"));
});

//当文件从上传队列移除后触发
//uploader.bind('FilesRemoved',function(uploader,files){
//    console.log(file);
//});

// 绑定文件上传进度事件
uploader.bind('UploadProgress',function(uploader,file){
	//console.log(file);
    $('#file-'+file.id+' .udl_bti .progress').css('width',file.percent + '%');//控制进度条
    $('#file-'+file.id+'-size').html('（'+ file.percent +'%）');//控制进度条
});

//plupload中为我们提供了mOxie对象
function previewImage(file,callback){//file为plupload事件监听函数参数中的file对象,callback为预览图片准备完成的回调函数
    if(!file || !/image\//.test(file.type)) return; //确保文件是图片
    if(file.type=='image/gif'){//gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
        var fr = new mOxie.FileReader();
        fr.onload = function(){
            callback(fr.result);
            fr.destroy();
            fr = null;
        }
        fr.readAsDataURL(file.getSource());
    }else{
        var preloader = new mOxie.Image();
        preloader.onload = function() {
            preloader.downsize( 300, 300 );//先压缩一下要预览的图片,宽300，高300
            var imgsrc = preloader.type=='image/jpeg' ? preloader.getAsDataURL('image/jpeg',80) : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
            callback && callback(imgsrc); //callback传入的参数为预览图片的url
            preloader.destroy();
            preloader = null;
        };
        preloader.load( file.getSource() );
    }	
}
//定义全局变量，用来记录总的文件上传数
var uploaded_num=0;
// 上传完成后触发
uploader.bind('FileUploaded',function(uploader,file,re){
    if (re.status==200) {
        if (re.response.indexOf('200|')>=0) {
            uploaded_num++;//成功上传的文件对总上传数做
            $('#file-'+file.id+' .udl_bti .file_delete').remove();//对成功上传的文件清除删除按钮
        }
    }
    //alert('上传完成！！');
	
    //$('#file-'+file.id+' .progress').text(responseObject.response);//结果
    //var jsonstr = responseObject.response;

    //var jsonArr = jsonstr.split('|');
    //var obj = eval('('+jsonstr+')');

    //$('#file-'+file.id+' .udl_bti').hide(); 
});

uploader.bind('Error',function(uploader,error ){
    alert('图片上传错误, 错误代码:'+error.code+', 错误信息:'+error.message+', 图片名称:'+error.file.name);
});

document.getElementById('start_upload').onclick = function(){
    uploader.start(); //调用实例对象的start()方法开始上传文件，当然你也可以在其他地方调用该方法
};

//当上传队列中所有文件都上传完成后触发
uploader.bind('UploadComplete',function(uploader,files){
    if (uploaded_num==0) {
        uploader.refresh();
        alert('图片未上传, 请选择图片进行上传！');
        $('.udl_bti .progress').hide();
    } else {
        var upladed = "成功上传"+uploader.total.uploaded+"张图片";
        var fail = "有"+uploader.total.failed+"张图片上传失败";
        alert('本次共上传图片'+uploaded_num+'张, 图片上传完成！！');
        uploaded_num = 0;
        $('.udl_bti .progress').hide();
        //$('.udl_bti .file_delete').remove();
        window.location.href=window.location.href;
    }
});
//删除文件，用于从库中读取出来的图片删除操作，真实删除
function filedelete(file,data_id, user_id){
    $.ajax( {
		url:'/m/works/delphoto',
		data:{
				id : data_id,
                user_id : <?php echo $agid?>
		},
		type:'post',
		cache:false,
		dataType:'json',
		success:function(res) {
			if(res.code == 200){
				 $(file).parent().parent().remove();
			}
		 }
	});
}
</script>
</html>